<template>
  <a-modal 
    :title="title" 
    :width="800" 
    :visible="visible" 
    :confirm-loading="confirmLoading" 
    cancel-text="关闭" 
    @ok="submit" 
    @cancel="closeModal"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否为平台红包">
          <a-radio-group v-model="merchantIdRadio">
            <a-radio :value="0">
              平台红包
            </a-radio>
            <a-radio :value="1">
              商家id：
              <a-input-number style="width: 200px" :min="1" placeholder="输入商家id" :disabled="merchantIdRadio == 0" v-model="merchantId" />
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="名称">
          <a-input v-decorator="['name', validatorRules.name ]" placeholder="请输入名称" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="优惠券数量">
          <a-radio-group v-model="totalRadio">
            <a-radio :value="0">
              无限制
            </a-radio>
            <a-radio :value="1">
              固定值：
              <a-input-number style="width: 200px" :min="1" placeholder="最低为1" :disabled="totalRadio == 0" v-model="total" />
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="单用户限领数量">
          <a-input-number style="width: 200px" :min="1" placeholder="最低为1" v-decorator="['limitCount', validatorRules.limitCount ]" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="红包类型">
          <a-radio-group v-model="discountRadio">
            <a-radio :value="0">
              满减优惠劵
            </a-radio>
            <a-radio :value="1" :disabled="merchantIdRadio == 0">
              折扣优惠劵：
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="满金额">
          <a-input-number 
            style="width: 200px" 
            placeholder="单位（元），例：一分钱，输入：0.01" 
            :formatter="(value) => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')" 
            :min="0" 
            v-decorator="['fullMoney', validatorRules.fullMoney]" 
            :precision="2" 
          />
        </a-form-item>
        <div v-show="discountRadio == 0">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="减金额">
            <a-input-number 
              style="width: 200px" 
              placeholder="单位（元），例：一分钱，输入：0.01" 
              :formatter="(value) => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')" 
              :min="0" 
              v-decorator="['minusMoney', {}]" 
              :precision="2" 
            />
          </a-form-item>
        </div>
        <div v-show="discountRadio == 1">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="折扣">
            <a-input-number style="width: 200px" :min="1" placeholder="9.5折请输入95" :disabled="discountRadio == 0" v-decorator="['discount', {}]" />
          </a-form-item>
        </div>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="有效期">
          <a-radio-group v-model="daysRadio">
            <a-radio :value="0">
              自领取后
            </a-radio>
            <a-radio :value="1">
              固定日期
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <div v-show="daysRadio == 0">
          <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="有效天数">
            <a-input-number style="width: 200px" :min="1" placeholder="最低为1" v-decorator="[ 'days', {}]" />
          </a-form-item>
        </div>
        <div v-show="daysRadio == 1">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" disabled label="使用券开始时间">
            <a-date-picker
              showTime
              format="YYYY-MM-DD"
              @change="startTimeChange"
              v-model="startTime"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="使用券截止时间">
            <a-date-picker
              showTime
              format="YYYY-MM-DD"
              @change="endTimeChange"
              v-model="endTime"
            />
          </a-form-item>
        </div>
        <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="优惠劵启用/禁用">
          <a-switch v-model="status" />
        </a-form-item>
        <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="适用类型">
          <a-radio-group v-model="applyType">
            <a-radio :value="1"> 门店通用 </a-radio>
            <a-radio :value="2"> 指定分类 </a-radio>
            <!-- <a-radio :value="3"> 指定商品 </a-radio> -->
          </a-radio-group>
        </a-form-item>
        <div v-if="applyType == 2">
          <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="指定分类">
            <a-tag color="blue" v-for="(item , index) in catIdList" :key="index">{{item.name}}</a-tag>
            <a-button type="primary" @click="funEditCat" icon="edit" size="small">选择类目</a-button>
          </a-form-item>
        </div>
        <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="发放类型">
          <a-radio-group v-decorator="[ 'sendType', validatorRules.sendType]">
            <a-radio :value="0"> 普通 </a-radio>
            <a-radio :value="1"> 注册赠送 </a-radio>
            <a-radio :value="2"> 首次收藏商家赠送 </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="备注">
          <a-textarea v-decorator="['remark', {} ]" placeholder="请输入备注" :rows="2" />
        </a-form-item>
      </a-form>
    </a-spin>
    <edit-cat-modal ref="editCatForm" @chooseCat="chooseCat"></edit-cat-modal>
  </a-modal>
</template>

<script>
import moment from 'moment'
import ApiTree from '@/api/market/couponList';
import ImageUpload from '@/components/ImageUpload';
import EditCatModal from '@/views/market/modules/editCatModal';
import { Slime } from '@/mixins/slime';
export default {
  name: 'couponListModal',
  components: { 
    ImageUpload,
    EditCatModal,
  },
  data() {
    return {
      title: '编辑',
      form: this.$form.createForm(this),
      model: {},
      validatorRules: {
        limitCount: { rules: [{ required: true, message: '请输入单用户限领数量!' }] },
        fullMoney: { rules: [{ required: true, message: '请输入满金额!' }] },
        sendType: { rules: [{ required: true, message: '请选择!' }],initialValue:0},
      },
      id: 0,
      //
      merchantIdRadio:0,
      merchantId:0,
      totalRadio:0,
      total:0,
      discountRadio:0,
      daysRadio:0,
      status:false,
      startTime:null,
      endTime:null,
      applyType:1,
      catIdList:[
        // {id:1,name:'类目名'}
      ],
    };
  },
  mixins: [Slime],
  methods: {
    // 增
    crudCreate() {
      this.crudUpdate({});
    },
    // 改
    crudUpdate(record) {
      const that = this;
      this.form.resetFields(); //重新设置领域
      this.model = Object.assign({}, record);
      this.visible = true;
      this.id = record.id
      this.$nextTick(() => {
        this.merchantIdRadio = record.merchantId == 0?0:1;
        this.merchantId = record.merchantId
        this.totalRadio = record.total == 0?0:1;
        this.total = record.total
        this.discountRadio = record.discount == 0?0:1;
        this.daysRadio = record.days == 0?1:0;
        this.status = record.status == 0?false:true
        this.applyType = record.applyType ? record.applyType : 1
        this.form.setFieldsValue({
          name: record.name,
          limitCount: record.limitCount,
          fullMoney: record.fullMoney?record.fullMoney/100:0,
          minusMoney: record.minusMoney?record.minusMoney/100:0,
          discount: record.discount,
          days: record.days,
          startTime: record.startTime,
          endTime: record.endTime,
          remark: record.remark,
        });
      });
      if(record.id){
        ApiTree.getDetail(record.id)
          .then((res) => {
            that.catIdList = res.result.catNames.map((obj)=>{
              return obj = {
                id:1,
                name: obj,
              }
            })
          })
          .finally(() => {
          });
      }
    },
    // 提交
    submit() {
      const that = this;
      this.form.validateFields((err, values) => {
        if (!err) {
          if(this.merchantIdRadio == 1 && !this.merchantId){
            that.$message.warning('请输入商家id');
            return false
          }else if(!values.name){
            that.$message.warning('请输入优惠券名称');
            return false
          }else if(this.totalRadio == 1 && !this.total){
            that.$message.warning('请输入优惠券数量');
            return false
          }else if(that.merchantIdRadio == 0 && that.discountRadio == 1){
            that.$message.warning('平台红包没有折扣优惠劵');
            return false
          }else if(that.discountRadio == 0 && !values.minusMoney){
            that.$message.warning('请输入减金额');
            return false
          }else if(that.discountRadio == 1 && !values.discount){
            that.$message.warning('请输入折扣');
            return false
          }else if(that.daysRadio == 0 && !values.days){
            that.$message.warning('请输入有效天数');
            return false
          }else if(that.daysRadio == 1 && !that.startTime){
            that.$message.warning('请输入劵开始时间');
            return false
          }else if(that.daysRadio == 1 && !that.endTime){
            that.$message.warning('请输入劵截止时间');
            return false
          }
          that.confirmLoading = true;
          //更改类型
          let applyIds = that.catIdList.map((obj)=>{
            return obj.id
          })
          applyIds = '['+applyIds.join(",")+']'
          let param = { 
            ...values,
            merchantId: that.merchantIdRadio == 0 ? 0 : that.merchantId,
            total: that.totalRadio == 0 ? 0 : that.total,
            fullMoney: that.numberRound(values.fullMoney),
            minusMoney: that.discountRadio == 0 ? that.numberRound(values.minusMoney) : 0,
            discount: that.discountRadio == 0 ? 0 : values.discount,
            days: that.daysRadio == 0 ? values.days : 0,
            startTime: that.daysRadio == 0 ? null : that.startTime,
            endTime: that.daysRadio == 0 ? null : that.endTime,
            status: that.status?0:1,
            applyType: that.applyType ? that.applyType : 1,
            applyIds: that.applyType == 2?applyIds : null,
          };
          if (!that.id) {
            that.submitCreate(param);
          } else { //没有编辑
            that.closeModal();
            // param = {...param, id:that.id}
            // that.submitUpdate(param);
          }
        }
      });
    },
    // 提交 增
    submitCreate(param) {
      const that = this;
      ApiTree.getAdd(param)
        .then((res) => {
          that.$message.success('新增成功');  
        })
        .finally(() => {
          that.closeModal();
        });
    },
    // 提交 改
    // submitUpdate(param) {
    //   const that = this;
    //   ApiTree.getUpdate(param)
    //     .then((res) => {
    //       that.$message.success('编辑成功');
    //     })
    //     .finally(() => {
    //       that.closeModal();
    //     });
    // },
    //修改类目
    funEditCat() {
      let catIdList = this.catIdList;
      this.$refs.editCatForm.open(catIdList);
    },
    //选择分类
    chooseCat(param){
      this.catIdList = param
    },
    // 弹窗-关闭
    closeModal() {
      this.confirmLoading = false;
      this.visible = false;
      this.form.resetFields();
      this.$emit('closeModal');
    },
    startTimeChange(date){
      let startTime = moment(date).format('YYYY-MM-DD');
      this.startTime = startTime
    },
    endTimeChange(date){
      let endTime = moment(date).format('YYYY-MM-DD');
      this.endTime = endTime
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>